#include "devicedriver.h"
#include "hmicommondefine.h"
#include <QDebug>
#if QT_VERSION<0x050000
#else
#include "frminput/frminput.h"
#include "virtualkeyboard.h"
#endif

DeviceDriver::DeviceDriver(MoveOperation *moveOperationIn, GlobalData *globalDataIn,QString workDirIn)
{
    moveOperation=moveOperationIn;
    globalData=globalDataIn;
    //******默认开启滚轮 与 按键声********************************
    volumPlayerFlag = EM_DEV_STATUS_ON;
    encoderFlag = EM_DEV_STATUS_ON;
    lastKey=Ros::E_KEY_NONE;

    qDebug()<<"DeviceDriver() start";
    //*******软键盘*********************************************

#if QT_VERSION<0x050000
    QWSServer::setCursorVisible(false);
    inputmethod = new INPUTMethod();
    QWSServer::setCurrentInputMethod(inputmethod);
#else
    inputmethod_qt5=frmInput::Instance();//有时候不显示，可能时隐藏到背面了吗？

//    auto keyboard = VirtualKeyBoard::getKeyboard();
//    keyboard->init(D_HMI_CHINESE_PYDB_PATH);

#endif

    //*******硬键盘 滚轮编码器************************************

    threadDev = new ThreadDev;
    connect(threadDev, SIGNAL(sendKeySignal(unsigned int, int)),this, SLOT(pendentKeyEvent_Slot(unsigned int, int)));
    threadDev->start();
    encoder = new ThreadEncoder;
    connect(encoder, SIGNAL(sendEncoderSig(unsigned short, int)),this, SLOT(KeyReadEncoderSlot(unsigned short, int)));
//    encoder->start();

    //*******jog运动信号*****************************************
    globalData = NULL;

    axisNumber = EM_AXIS_END;
    direction = EM_DIRECTION_END;

    //*******锁屏信号*****************************************
    lockWin = false;

    //*******滚轮运动信号**************************************
    wheelTimer = new QTimer;
    connect(wheelTimer,SIGNAL(timeout()),this,SLOT(wheelTimeWork()));

    wheelFlag = false;

}

void DeviceDriver::setBuzzerPlay_slot()
{
    threadDev->setBuzzerPlay_slot();
}

//滚轮运动定时器
void DeviceDriver::wheelTimeWork()
{
    if(wheelFlag)
    {
        wheelFlag=false;

        if(!moveOperation->isJogTimerActive())
        {
            moveOperation->startJogMove(axisNumber,direction);
        }
    }
    else
    {
        moveOperation->stopJogMove();

        //类似喂狗
        wheelTimer->stop();
    }
}



void DeviceDriver::pendentKeyEvent_Slot(unsigned int nKey, int nValue)
{

    static  int nLockTime = 0;

    qDebug()<<"pendentKeyEvent_Slot:nKey"<<nKey<<"nValue"<<nValue;


    #if QT_VERSION<0x050000
        // 隐藏键盘
        inputmethod->HideKeyBoard();
    #endif


    if(Ros::E_KEY_LOCK == nKey)
    {
        qDebug()<<"Ros::E_KEY_LOCK "<<nValue;
        if(nValue == 1)
        {
            nLockTime++;
        }
        if(nLockTime == 3)
        {
            nLockTime = 0;
            if(lockWin)
            {
                //解锁
                lockWin = false;
                emit closeBoxSignal();

            }
            else
            {
                //加锁
                lockWin = true;
                emit msgBoxSignal(EM_MSG_BOX_NO_BTN,tr("锁屏"),tr("屏幕已锁定\n解锁请按锁屏按钮3次"));
                frmInput::Instance()->showPanelView(true);
            }
            return;

        }
    }


    // 锁机状态
    if(lockWin)
    {
        return;//下面所有操作都禁止
    }


    switch(nKey)
    {
    case Ros::E_KEY_NONE:
    {
        qDebug()<<"Ros::key_none"<<nValue;

       if(nValue == 0)//松开
        {
           if(Ros::E_KEY_START_RUN==lastKey)
           {
               emit keyStartRelease();
           }
           else if(Ros::E_KEY_RIGHT_FUN2_LMOVE==lastKey)
           {
               emit keyFunctionR2Release();
           }
           else if(Ros::E_KEY_RIGHT_FUN3_JMOVE==lastKey)
           {
               emit keyFunctionR3Release();
           }
           else if(Ros::E_KEY_AXIS1_N==lastKey||Ros::E_KEY_AXIS1_P==lastKey
                   ||Ros::E_KEY_AXIS2_N==lastKey||Ros::E_KEY_AXIS2_P==lastKey
                   ||Ros::E_KEY_AXIS3_N==lastKey||Ros::E_KEY_AXIS3_P==lastKey
                   ||Ros::E_KEY_AXIS4_N==lastKey||Ros::E_KEY_AXIS4_P==lastKey
                   ||Ros::E_KEY_AXIS5_N==lastKey||Ros::E_KEY_AXIS5_P==lastKey
                   ||Ros::E_KEY_AXIS6_N==lastKey||Ros::E_KEY_AXIS6_P==lastKey)
           {
               moveOperation->stopJogMove();
           }

        }

    }
        break;
    case Ros::E_KEY_START_RUN:
    {
        //qDebug()<<"Ros::key1"<<nValue;

        if(nValue == 1)//按下
        {
//            moveOperation->setJogFlag();
            emit keyStartPress();
        }
        else if(nValue == 0)//松开
        {
            emit keyStartRelease();
        }

    }
        break;
    case Ros::E_KEY_STOP:
    {
        //qDebug()<<"Ros::key2"<<nValue;
        if(nValue == 1)//按下
        {
            emit keyStop();
        }
    }
        break;
    case Ros::E_KEY_CEASE:
    {
        //qDebug()<<"Ros::key3"<<nValue;

        if(nValue == 1)//按下
        {
            emit keyPause();
        }

    }
        break;
    case Ros::E_KEY_RETURN_ZERO:
    {
        //qDebug()<<"Ros::key4"<<nValue;

        if(nValue == 1)//按下
        {
            emit keyReturnZero();
        }



    }
        break;

    case Ros::E_KEY_PALY_VOICE:
    {
        //qDebug()<<"Ros::6"<<nValue;
        if(nValue == 1)//按下
        {
            if(volumPlayerFlag == EM_DEV_STATUS_OFF)
            {
                volumPlayerFlag = EM_DEV_STATUS_ON;
            }
            else
            {
                volumPlayerFlag = EM_DEV_STATUS_OFF;
            }
        }
    }
        break;
    case Ros::E_KEY_AXIS1_N:
    {
        //qDebug()<<"Ros:9"<<nValue;

        if(nValue == 1)//按下
        {
            //qDebug("pushButton_L1_pressed");
            axisNumber = EM_AXIS_1;
            direction = EM_DIRECTION_LEFT;
            emit setRightViewCurrentAxis(EM_AXIS_1);

            //jogTimer->start(JOG_TIME);
            //新方法:
            moveOperation->startJogMove(axisNumber,direction);

        }
        else if(nValue == 0)//松开
        {
            moveOperation->stopJogMove();
        }

    }
        break;
    case Ros::E_KEY_AXIS1_P:
    {
        //qDebug()<<"Ros::10"<<nValue;

        if(nValue == 1)//按下
        {
            //qDebug("pushButton_L1_pressed");
            axisNumber = EM_AXIS_1;
            direction = EM_DIRECTION_RIGHT;
            emit setRightViewCurrentAxis(EM_AXIS_1);

            //jogTimer->start(JOG_TIME);
            //新方法:
            moveOperation->startJogMove(axisNumber,direction);
        }
        else if(nValue == 0)//松开
        {
            moveOperation->stopJogMove();
        }
    }
        break;
    case Ros::E_KEY_AXIS2_N:
    {
        //qDebug()<<"Ros::11"<<nValue;
        if(nValue == 1)//按下
        {
            //qDebug("pushButton_L1_pressed");
            axisNumber = EM_AXIS_2;
            direction = EM_DIRECTION_LEFT;
            emit setRightViewCurrentAxis(EM_AXIS_2);

            //jogTimer->start(JOG_TIME);
            //新方法:
            moveOperation->startJogMove(axisNumber,direction);
        }
        else if(nValue == 0)//松开
        {
            moveOperation->stopJogMove();
        }
    }
        break;
    case Ros::E_KEY_AXIS2_P:
    {
        //qDebug()<<"Ros::12"<<nValue;

        if(nValue == 1)//按下
        {
            //qDebug("pushButton_L1_pressed");
            axisNumber = EM_AXIS_2;
            direction = EM_DIRECTION_RIGHT;
            emit setRightViewCurrentAxis(EM_AXIS_2);

            //jogTimer->start(JOG_TIME);
            //新方法:
            moveOperation->startJogMove(axisNumber,direction);
        }
        else if(nValue == 0)//松开
        {
            moveOperation->stopJogMove();
        }
    }
        break;
    case Ros::E_KEY_AXIS3_N:
    {
        //qDebug()<<"Ros::13"<<nValue;

        if(nValue == 1)//按下
        {
            //qDebug("pushButton_L1_pressed");

            axisNumber = EM_AXIS_3;
            direction = EM_DIRECTION_LEFT;
            emit setRightViewCurrentAxis(EM_AXIS_3);

            //jogTimer->start(JOG_TIME);
            //新方法:
            moveOperation->startJogMove(axisNumber,direction);
        }
        else if(nValue == 0)//松开
        {
            moveOperation->stopJogMove();
        }
    }
        break;
    case Ros::E_KEY_AXIS3_P:
    {
        //qDebug()<<"Ros::14"<<nValue;

        if(nValue == 1)//按下
        {
            //qDebug("pushButton_L1_pressed");

            axisNumber = EM_AXIS_3;
            direction = EM_DIRECTION_RIGHT;
            emit setRightViewCurrentAxis(EM_AXIS_3);

            //jogTimer->start(JOG_TIME);
            //新方法:
            moveOperation->startJogMove(axisNumber,direction);
        }
        else if(nValue == 0)//松开
        {
            moveOperation->stopJogMove();
        }
    }
        break;
    case Ros::E_KEY_AXIS4_N:
    {
        //qDebug()<<"Ros::15"<<nValue;

        if(nValue == 1)//按下
        {
            //qDebug("pushButton_L1_pressed");

            axisNumber = EM_AXIS_4;
            direction = EM_DIRECTION_LEFT;
            emit setRightViewCurrentAxis(EM_AXIS_4);

            //jogTimer->start(JOG_TIME);
            //新方法:
            moveOperation->startJogMove(axisNumber,direction);
        }
        else if(nValue == 0)//松开
        {
            moveOperation->stopJogMove();
        }
    }
        break;
    case Ros::E_KEY_AXIS4_P:
    {
        //qDebug()<<"Ros::16"<<nValue;

        if(nValue == 1)//按下
        {
            //qDebug("pushButton_L1_pressed");

            axisNumber = EM_AXIS_4;
            direction = EM_DIRECTION_RIGHT;
            emit setRightViewCurrentAxis(EM_AXIS_4);

            //jogTimer->start(JOG_TIME);
            //新方法:
            moveOperation->startJogMove(axisNumber,direction);
        }
        else if(nValue == 0)//松开
        {
            moveOperation->stopJogMove();
        }
    }
        break;
    case Ros::E_KEY_AXIS5_N:
    {
        //qDebug()<<"Ros::17"<<nValue;

        if(nValue == 1)//按下
        {
            //qDebug("pushButton_L1_pressed");

            axisNumber = EM_AXIS_5;
            direction = EM_DIRECTION_LEFT;
            emit setRightViewCurrentAxis(EM_AXIS_5);

            //jogTimer->start(JOG_TIME);
            //新方法:
            moveOperation->startJogMove(axisNumber,direction);
        }
        else if(nValue == 0)//松开
        {
            moveOperation->stopJogMove();
        }
    }
        break;
    case Ros::E_KEY_AXIS5_P:
    {
        //qDebug()<<"Ros::18"<<nValue;

        if(nValue == 1)//按下
        {
            //qDebug("pushButton_L1_pressed");

            axisNumber = EM_AXIS_5;
            direction = EM_DIRECTION_RIGHT;
            emit setRightViewCurrentAxis(EM_AXIS_5);

            //jogTimer->start(JOG_TIME);
            //新方法:
            moveOperation->startJogMove(axisNumber,direction);
        }
        else if(nValue == 0)//松开
        {
            moveOperation->stopJogMove();
        }
    }
        break;
    case Ros::E_KEY_AXIS6_N:
    {
        //qDebug()<<"Ros::19"<<nValue;

        if(nValue == 1)//按下
        {
            //qDebug("pushButton_L1_pressed");

            axisNumber = EM_AXIS_6;
            direction = EM_DIRECTION_LEFT;

            emit setRightViewCurrentAxis(EM_AXIS_6);

            //jogTimer->start(JOG_TIME);
            //新方法:
            moveOperation->startJogMove(axisNumber,direction);
        }
        else if(nValue == 0)//松开
        {
            moveOperation->stopJogMove();
        }
    }
        break;
    case Ros::E_KEY_AXIS6_P:
    {
        //qDebug()<<"Ros::20"<<nValue;
        if(nValue == 1)//按下
        {
            //qDebug("pushButton_L1_pressed");

            axisNumber = EM_AXIS_6;
            direction = EM_DIRECTION_RIGHT;
            emit setRightViewCurrentAxis(EM_AXIS_6);


            //jogTimer->start(JOG_TIME);
            //新方法:
            moveOperation->startJogMove(axisNumber,direction);
        }
        else if(nValue == 0)//松开
        {
            moveOperation->stopJogMove();
        }
    }
        break;
    case Ros::E_KEY_RIGHT_FUN1_SHIFT:
    {
        //qDebug()<<"Ros::21"<<nValue;
        if(nValue == 1)//按下
        {
            emit keyFunctionR1Press();
        }
        else if(nValue == 0)//松开
        {

        }
    }
        break;
    case Ros::E_KEY_RIGHT_FUN2_LMOVE:
    {
        //qDebug()<<"ros::key22";
        if(nValue == 1)//按下
        {
            emit keyFunctionR2Press();
        }
        else if(nValue == 0)//松开
        {
            emit keyFunctionR2Release();
        }

    }
        break;
    case Ros::E_KEY_RIGHT_FUN3_JMOVE: //示教器右下角的按钮按下,执行按下使能开关后,执行 关节到点 功能
    {
        //qDebug()<<"ros::key23";
        if(nValue == 1)//按下
        {
            emit keyFunctionR3Press();
        }
        else if(nValue == 0)//松开
        {
            emit keyFunctionR3Release();
        }
    }
        break;
    case Ros::E_KEY_Vel_INCREASE:
    {
        if(nValue == 1)//按下
        {
            emit velIncrease_signal();
        }
    }
        break;
    case Ros::E_KEY_Vel_DECREASE:
    {
        if(nValue == 1)//按下
        {
            emit velDecrease_signal();
        }
    }
        break;
    case Ros::E_KEY_STEP_MODE_CHANGE:
    {
        if(nValue == 1)//按下
        {
            emit stepModeChange_signal();
        }
    }
        break;
    case Ros::E_KEY_JOG_COORDINATE_CHANGE:
    {
        if(nValue == 1)//按下
        {
            emit jogCoordinateChange_signal();
        }
    }
        break;
    case Ros::E_KEY_JOG_COORDINATE_TOOL:
    {
        if(nValue == 1)//按下
        {
            emit jogCoordinateChangeTool_signal();
        }
    }
        break;
    case Ros::E_KEY_CLEAR_MESSAGE:
    {
        if(nValue == 1)//按下
        {
            emit clearMessage_signal();
        }
    }
        break;
    case Ros::E_KEY_SERVO_ON:
    {
        if(nValue == 1)//按下
        {
            emit servoOn_signal(1);
        }
    }
        break;
    case Ros::E_KEY_ROBOT_CHANGE:
    {
        if(nValue == 1)//按下
        {
            emit robotChange_signal();
        }
    }
        break;
    default:
        break;
    }
    lastKey=(Ros::E_KEY)nKey;
}

void DeviceDriver::KeyReadEncoderSlot(unsigned short code, int val)
{
    //qDebug()<<"KeyReadEncoderSlot0 "<<val;      //val值 反应速率
    if(encoderFlag == EM_DEV_STATUS_OFF)        //如果标志位 关闭 则不执行操作
    {
        return;
    }
//    if(this->isHidden())
//    {
//        return;
//    }
//    if(!m_pCustomInstace)
//    {
//        return;
//    }
//    if(!m_pCUrTam)
//    {
//        return;
//    }
//    if(!InputRegDlg)
//    {
//        return;
//    }
    // >0
//    qDebug()<<"KeyReadEncoderSlot1";
//    if(m_bIsInitData || (m_pCustomInstace->m_pnAllFlagList[EM_AFT_TERMINATE_OVER_LAYER] == EM_CF_ON))
//    {
//        return;
//    }
//    qDebug()<<"KeyReadEncoderSlot2";

#if QT_VERSION<0x050000
    // 隐藏键盘
    if( inputmethod ) //非空
    {
        inputmethod->HideKeyBoard();
    }
#endif

//    qDebug()<<"KeyReadEncoderSlot3";
    // 限制控制
//    if(!m_pCustomInstace->GetExecCtrlFlag(EM_EXEC_CTRL_FLAG_WHOLE))
//    {
//        return;
//    }
//    qDebug()<<"KeyReadEncoderSlot4";

    // 锁机状态
    if(lockWin)
    {
        return;//下面所有操作都禁止
    }
//    if(m_nLockStatus == EM_SYS_LOCK_LOCKED)
//    {
//        if(InputRegDlg->isHidden())
//        {
//            //m_pCustomToolDefine->ShowInputRegeditNumber();
//            m_pCustomInstace->m_psDialogTable->m_emBeShowId = EM_DIF_InputRegistrationDialog;
//            return;
//        }
//    }
//    qDebug()<<"KeyReadEncoderSlot5";

    if( code == Ros::forward)
    {
//        // 正
//        m_pCUrTam->SetHandWheel(m_pCustomInstace->m_nAxisNumber,EM_MDF_POSITIVE,val);
//        // 设置滚轮滚动标志
//        m_nWholeRunFlag = EM_CF_ON;
        // 初始化等待时间
//        m_nWholeRunTime = 0;

        //qDebug()<<"+++++++++++++++";
        wheelFlag = true;

        direction = EM_DIRECTION_LEFT;
        if(!wheelTimer->isActive())
        {
//            if(globalData->tryLock(TRYLOCKTIME))
//            {
                if(globalData->globalCurrentState == ENUM_COMMAND_RUN || globalData->globalCurrentState == ENUM_COMMAND_CEASE)
                {
//                    globalData->unlock();
                    emit msgBoxSignal(EM_MSG_BOX_SURE_BTN,tr("提示"),tr("当前状态不可以使用滚轮"));
                    return ;
                }

                axisNumber = globalData->currentUseAxis;
//                globalData->unlock();
//            }
            wheelTimer->start(250);
        }

        emit sendHandWheel(axisNumber,direction,val);

    }
    else if(code == Ros::back)
    {
//        // 负
//        m_pCUrTam->SetHandWheel(m_pCustomInstace->m_nAxisNumber,EM_MDF_MINUS,val);
//        Debug_Print("Encoder code:%d,val:%d",code,val);

//        // 设置滚轮滚动标志
//        m_nWholeRunFlag = EM_CF_ON;
//        // 初始化等待时间
//        m_nWholeRunTime = 0;
        //qDebug()<<"---------------";
        wheelFlag = true;

        direction = EM_DIRECTION_RIGHT;
        if(!wheelTimer->isActive())
        {
//            if(globalData->tryLock(TRYLOCKTIME))
//            {
                if(globalData->globalCurrentState == ENUM_COMMAND_RUN || globalData->globalCurrentState == ENUM_COMMAND_CEASE)
                {
//                    globalData->unlock();
                    emit msgBoxSignal(EM_MSG_BOX_SURE_BTN,tr("提示"),tr("当前状态不可以使用滚轮"));
                    return ;
                }

                axisNumber = globalData->currentUseAxis;
//                globalData->unlock();
//            }
            wheelTimer->start(250);
        }


        emit sendHandWheel(axisNumber,0,val);
    }
    //qDebug()<<"KeyReadEncoderSlot6";
}
